




//
//  ZCartViewController.m
//  ZQLearn
//
//  Created by 朵 on 2019/5/7.
//  Copyright © 2019 macfeel. All rights reserved.

#import "CartModel.h"
#import "ZPayViewController.h"
#import "ZCartViewController.h"
#import "CartCell.h"
#import "CartPayBarView.h"
//#import "ZPayViewController.h"
@interface ZCartViewController ()
<UITableViewDelegate,UITableViewDataSource,BottomPayDelegate,CartCellDelegate,UIAlertViewDelegate>

@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)NSMutableArray *dataArray;
///刷新和加载更多时候用
@property (nonatomic,assign)NSInteger currentPage;

@property(nonatomic,assign)BOOL isEdit;
@property(nonatomic,assign)BOOL isTickAll;
@property(nonatomic,assign)BOOL isTapMinusOrPlus;
///总金额
@property(nonatomic,assign)float totalMoney;

///底部计算条
@property (nonatomic,strong)CartPayBarView *payView;

///当前商品id
@property(nonatomic,copy)NSString *currentCommodityId;

@end

@implementation ZCartViewController
#define cellIdentifier @"cart"
////表样板
-(UITableView *)tableView{
    if (!_tableView) {
        
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0 , 0, ScreenWidth , ScreenHeight -60-64) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.rowHeight = 100.f;
        _tableView.backgroundColor = kBackgroundColor;
        [_tableView registerNib:[UINib nibWithNibName:@"CartCell" bundle:nil] forCellReuseIdentifier:cellIdentifier];
        
        WeakStament(ws);
        //        _tableView.mj_header = [CustomRefreshHeader headerWithRefreshingBlock:^{
        //            [ws loadData];
        //        }];
        //        _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        //            [ws loadMoreData];
        //        }];
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.tableFooterView = [UIView new];
    }
    return _tableView;
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [UserModel shareInstance].isCart = YES;
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
     [UserModel shareInstance].isCart = false;
    
}
- (void)viewDidLoad {
    
    [super viewDidLoad];
    [self.navigationItem setItemWithTitle:@"购物车" textColor:kNavigationTitleColor fontSize:18 itemType:center];
    [self addNavgationRightButtonWithFrame:CGRectMake(0, 0, 30, 30) title:@"编辑" Image:@"" selectedIMG:@"" tartget:self action:@selector(editAction:)];
    self.dataArray = [NSMutableArray array];
    [self.view addSubview:self.tableView];
    
    
    ///看过来这样加
    self.payView = [[[NSBundle mainBundle] loadNibNamed:@"CartPayBarView" owner:self options:nil] lastObject];
    self.payView.delegate = self;
    self.payView.frame = CGRectMake(0,ScreenHeight-64-60, ScreenWidth, 60);
    [self.view addSubview:self.payView];
    [self.view bringSubviewToFront:self.payView];
    
    [self loadData];
    
    ///编辑初始状态
    self.isEdit = NO;
    // Do any additional setup after loading the view.
}

///点击编辑完成按钮
- (void)editAction:(UIButton *)button{
    
    button.selected = !button.selected;
    ////这里是否点击编辑是编辑状态的起点
    [self modifyStatusWithEditStatus:button.selected];
    [self refreshUIWtihEditStatus:self.isEdit];
    if (button.selected) {
        // 点击了编辑按钮，进入编辑状态
        [button setTitle:@"完成" forState:UIControlStateNormal];
    }else{
        // 点击了完成按钮，进入完成状态
        [button setTitle:@"编辑" forState:UIControlStateNormal];
        //        if (self.isTapMinusOrPlus) {
        //            [self request_sendLatestCartData];
        //        }
    }
    [button setTitleColor:kWhiteColor forState:UIControlStateNormal];
}


- (void)modifyStatusWithEditStatus:(BOOL)isEdit
{
    ///点击编辑时做了标记
    self.isEdit = isEdit;
    YYLog(@"%i",isEdit);
    if (isEdit) {
        self.isTapMinusOrPlus = NO;
    }
}

///根据编辑的状态来改变底部视图的显示
- (void)refreshUIWtihEditStatus:(BOOL)isEdit{
    
    [self.tableView reloadData];
    [self updatePayViewWithEditStatus:isEdit];
    
}
-(void)loadData{
//    userInfo.id = "2c913a7965a7ba510165a81dab350003",
//    pageSize = 10,
//    pageIndex = 1,
    if (self.currentPage==1) {
        [self.dataArray removeAllObjects];
    }
    NSDictionary *dict = @{@"pageIndex":@(1),@"userInfo.id":[UserInfoSave shareInstance].uid?:@"",@"pageSize":@(10),};
    [ZNetworkService postRequestWithBaseUrl:kCartListUrl setParameters:dict success:^(id result) {
        YYLog(@"%@",result);
        
        if ([result[@"errorCode"]integerValue]==0) {
            NSArray *arr = result[@"result"];
            for (NSDictionary *dic in arr) {
                CartModel *model = [CartModel mj_objectWithKeyValues:dic];
                [self.dataArray addObject:model];
            }
            [self.tableView reloadData];
            
            [self updatePayViewWithEditStatus:self.isEdit];
            
        }else{
            //            [AFToast showText: @"添加失败"];
        }
    } fail:^(NSError *error) {
        
    } delegater:nil];
    
}



#pragma delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    //    ZMsgDetailViewController *det = [ZMsgDetailViewController new];
    //
    //    [self.navigationController pushViewController:det animated:YES];
}

#pragma mark - datasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    CartModel *model = self.dataArray[indexPath.row];
    CartCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
    
    cell.nameLab.text = model.commodityInfo[@"title"];
    cell.scoreLab.text = [NSString stringWithFormat:@"%@积分",model.commodityInfo[@"integral"]];
    [cell.headImg sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",kStorePicServerUrl,model.commodityInfo[@"photo"]]] placeholderImage:nil];
    cell.delegate = self;
    cell.indexPath = indexPath;
    cell.model = self.dataArray[indexPath.row];
    cell.isEdit = self.isEdit;
    //    if (self.isTickAll==YES) {
    //        //点击全选按钮
    //        cell.tickBtn.selected = YES;
    //    }else{
    //        cell.tickBtn.selected = NO;
    //    }
    
    return cell;
}



- (void)loadMoreData{
    self.currentPage++;
    //    [self loadData];
}


- (void)endRefresh{
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
}


///没有更多数据
- (void)noMoreData {
    [self.tableView reloadData];
    [self.tableView.mj_footer endRefreshingWithNoMoreData];
}
#pragma mark - cartcell delegate
///点击勾选按钮
-(void)cartCell:(CartCell *)cell didCilckedTickButton:(BOOL)selected atIndexPath:(NSIndexPath *)indexPath{
    
    
    CartModel *model = self.dataArray[indexPath.row];
    model.isSelected = selected;
    [self updatePayViewWithEditStatus:self.isEdit];
    
}


///这个方法要共用
- (void)updatePayViewWithEditStatus:(BOOL)isEdit{
    self.payView.sumLabel.hidden = isEdit;
    self.payView.scoreLab.hidden = isEdit;
    self.payView.amountLabel.hidden = isEdit;
    if (isEdit) {
        // 点击了编辑按钮，进入编辑状态
        [_payView.payBtn setTitle:@"删除" forState:UIControlStateNormal];
        [_payView.payBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
    }else{
        // 点击了完成按钮，进入完成状态
        [_payView.payBtn setTitle:@"结算" forState:UIControlStateNormal];
        [_payView.payBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, -20, 0, 0)];
    }
    
    float amount = 0.00;
    int quantityOfGoodsSelected = 0;
    // 价格、结算数计算
    for (CartModel * model in self.dataArray) {
        if (model.isSelected) {
            ///总价=单价*数量
            NSString *price =  model.commodityInfo[@"integral"];
            NSInteger priceInt = [price integerValue];
            YYLog(@"%@***%ld",price,priceInt);
            if (model.product_num==0) {
                //因为初次进来的时候确实没有，但是添加购物车时候默认肯定时1
                model.product_num = 1;
            }
            amount += priceInt * model.product_num;
            //记录选择的商品的数量
            quantityOfGoodsSelected += model.product_num;
            YYLog(@"总打勾数目:%d",quantityOfGoodsSelected);
            YYLog(@"%d",quantityOfGoodsSelected);
        }
    }
    
    ///判断总打勾数和数组中的个数是否一致，如果一致则全选按钮勾上
    if (self.dataArray.count==quantityOfGoodsSelected) {
        self.payView.tickBtn.selected = YES;
    }else{
        self.payView.tickBtn.selected = false;
    }
    
    ////sumLabel 这个label 是合计的汉字的写死的label
    _payView.scoreLab.text = [NSString stringWithFormat:@"%.1f积分",amount];
    _payView.amountLabel.text = [NSString stringWithFormat:@"(%d)", quantityOfGoodsSelected];
    
}

//点击加减号时调用的代理
- (void)cartCell:(CartCell *)cell didChangeGoodsNumber:(NSInteger)num andProductId:(NSInteger)productId atIndexPath:(NSIndexPath *)indexPath{
    
    self.isTapMinusOrPlus = YES;
    ///点击加减号时进行数量的记录
    CartModel *currentModel = self.dataArray[indexPath.row];
    currentModel.product_num = num;
    
    ///根据数量计算应付金额
    CGFloat sumRMB = 0;
    int quantityOfGoodsSelected = 0;
    for (int i=0; i<self.dataArray.count; i++) {
        CartModel *model = self.dataArray[i];
        if (model.isSelected) {
            NSString *price =  model.commodityInfo[@"integral"];
            NSInteger priceInt = [price integerValue];
            sumRMB += model.product_num*priceInt;
            quantityOfGoodsSelected += model.product_num;
            self.totalMoney = sumRMB;
            
        }
    }
    _payView.scoreLab.text = [NSString stringWithFormat:@"%.1f积分",sumRMB];
    _payView.amountLabel.text = [NSString stringWithFormat:@"(%d)", quantityOfGoodsSelected];
}

#pragma mark - payBottomDelegate
#pragma mark - 全选按钮
-(void)tickAllButtonClicked:(UIButton *)btn{
    YYLog(@"%@",btn);
    if (_payView.tickBtn.selected) {
        //        self.isTickAll = YES;
        float sum = 0;//定义总价
        NSInteger allNum = 0;
        for (CartModel *model in self.dataArray) {
            
            model.isSelected = YES;//之前这句代码没有加
            ///必须这样分开写，否则乘出来有问题
            
            NSString *price =  model.commodityInfo[@"integral"];
            NSInteger priceInt = [price integerValue];
            ///首次进来，默认时1，没有选，所以手动给他加成1
            if (model.product_num==0) {
                model.product_num = 1;
            }
            sum += priceInt * model.product_num;
            allNum += model.product_num;///++是个很牛逼的用法
        }
        
        _payView.scoreLab.text = [NSString stringWithFormat:@"￥%.1f", sum];
        _payView.amountLabel.text = [NSString stringWithFormat:@"(%ld)",allNum];
        
        //是为了在全选后再取勾选某一个取消选择时候从总价中减去那个被取消选择的商品价格
        self.totalMoney = sum;
        
    }else{
        
        //        self.isTickAll = NO;
        for (CartModel *model in self.dataArray) {
            model.isSelected = NO;
        }
        _payView.scoreLab.text = @"0.0积分";
        _payView.amountLabel.text = @"(0)";
    }
    
    [self.tableView reloadData];
}

#pragma mark - 购物车商品删除
-(void)payButtonClicked:(UIButton *)btn{
    //
    YYLog(@"点击购买或者删除");
    if (self.isEdit==YES) {
        //执行删除操作
        [self alert:@"确定要删除所选商品"];
        
    }else if(self.isEdit==NO){
        
        //结算操作
        NSString *temp = _payView.amountLabel.text;
        
        if ([temp isEqualToString:@"(0)"]||temp.length==0) {
            
            [self alert:@"请选择您要结算的商品"];
            return;
        }
        
//        [_transArray removeAllObjects];
//
//        for (CartModel *model in _dataArray) {
//
//            if (model.isSelected) {
//
//                [_transArray addObject:model];
//
//            }
//        }
        
        ZPayViewController *pay = [ZPayViewController new];
        pay.strAmount = [NSString stringWithFormat:@"%.0f",self.totalMoney];
        [self.navigationController pushViewController:pay animated:YES];
//        ConfirmOrderViewController *confirm = [[ConfirmOrderViewController alloc]init];
//        confirm.hidesBottomBarWhenPushed = YES;
//        confirm.yunfee = _payView.yunFeeLabel.text;
//        NSString * sumPrice = [_payView.sumPriceLabel.text substringFromIndex:1];
//        NSString * yunfei = [_payView.yunFeeLabel.text substringFromIndex:1];
//        if (yunfei.intValue > 0) {
//            confirm.money = [NSString stringWithFormat:@"%.2f", sumPrice.floatValue + yunfei.floatValue];
//        } else {
//            confirm.money = _payView.sumPriceLabel.text;
//        }
//
//        confirm.receiveArray = [_transArray copy];
//        confirm.valueBlock = ^(NSString *valueString){
//
//            self.flag = valueString;
//
//        };
//        confirm.isComeFromShoppingCart = YES;
//        [self.navigationController pushViewController:confirm animated:YES];
//
    }
    
//    ZPayViewController *pay = [ZPayViewController new];
//    [self.navigationController pushViewController:pay animated:YES];
}

- (void)alert:(NSString *)msg{
    
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:msg delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alert show];
    
}

#pragma mark - alertView delegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    //点击确定执行删除操作
    if (buttonIndex==1) {
        
//        NSMutableString *deleteProductString = [NSMutableString string];
        ///如果多选删除，可以存放多个id
        
        NSMutableArray *tempArray = [NSMutableArray array];
        for (CartModel * model in self.dataArray) {
            if (model.isSelected) {
                self.currentCommodityId = model.commodityInfo[@"id"];
                NSString *currentId = model.commodityInfo[@"id"];
                [tempArray addObject:currentId];
                YYLog(@"%@",tempArray);

                [self deleteFromCart:tempArray];
            }
        }
        
//        if (deleteProductString.length>0) {
//            [deleteProductString deleteCharactersInRange:NSMakeRange(deleteProductString.length-1, 1)];
//        }
        
    }
}


//问题接口
///购物车删除

- (void)deleteFromCart:(NSArray *)array{
    ///系统方法 对象转成json 串
//    NSData *data=[NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:nil];
//    NSString *jsonStr=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    
    ////mj 方法 数组转json  字典转json  对象转json
    NSString *jsonString = [array mj_JSONString];
    
    NSDictionary *para = @{@"ids":jsonString};
//    NSMutableArray *arr = [NSMutableArray array];
//    [arr addObject:@"234"];
//    YYLog(@"arr ======= %@", arr);
    [ZNetworkService getRequestWithBaseUrl:kDeleteFromCartUrl setParameters:para success:^(id result) {
        YYLog(@"%@",result);
    } fail:^(NSError *error) {
        
    } delegater:nil];
//    [[Network sharedInstace]postWithSectionalUrl:kDeleteCartUrl parameters:para isShowProgressHUD:YES successBlock:^(NSDictionary *responseObject) {
//
//        if ([responseObject isKindOfClass:[NSDictionary class]]) {
//            NSDictionary *dic = (NSDictionary *)responseObject;
//            if ([dic[@"code"]isEqualToString:@"1000"]) {
//                NSMutableArray * arrTemp = [NSMutableArray array];
//                for (CartModel * model in self.dataArray) {
//                    if (model.isSelected) {
//                        [arrTemp addObject:model];
//                    }
//                }
//                [self.dataArray removeObjectsInArray:arrTemp];
//                [self.tableView reloadData];
//
//                if (self.dataArray.count==0) {
//                    self.bgView.hidden = NO;
//                    self.emptyCartTip.hidden = NO;
//                    self.loginBtn.hidden = YES;
//                    self.myCollectionBtn.hidden = NO;
//                }
//                //                    [self.tableView reloadData];
//                //                    [ToolClass totalcartMinus:_dataArray.count];
//            }
//        }
//
//    } failureBlock:^(NSError *error) {
//
//    }];
}


@end
